// import { GetFieldDecoratorOptions } from "antd/lib/form/Form";
import { addon, Permission } from "pao-aop";
import { reactControl, ReactView, ReactViewControl, ReactViewState } from "pao-aop-client";
import React from "react";
// import { InputType } from "src/business/components/buss-components/form-creator";
import { MainContent } from "src/business/components/style-components/main-content";
import { AppServiceUtility } from 'src/projects/app/appService';
// import { edit_props_info } from "src/projects/app/util-tool";
import { Steps, Result, Card, message, Row, Button, Table, Modal, Col, Pagination } from 'antd';
import { request } from "../../../../../business/util_tool";
// import { remote } from 'src/projects/remote';
import ApplyTemplateForm from "./apply-template";
import { ApplyInfo } from "./apply-info";
import { SocietyInfo } from "./society-info";
import { ROUTE_PATH } from "src/projects/router";
import "./index.less";
import TextArea from "antd/lib/input/TextArea";
import Search from "antd/lib/input/Search";
const { Step } = Steps;

/**
 * 组件：个人募捐申请页面状态
 */
export interface RecipientApplyState extends ReactViewState {
    /**
     * 申请状态
     */
    step?: number;
    status?: string;
    /**
     * 表单权限控制
     */
    disabled?: boolean;
    /** 接口名 */
    request_url?: string;
    // 详情
    apply_info?: any;
    // 慈善会信息
    society_info?: any;
    /** 模板列表 */
    template_list?: any;
    // 模板ID
    template_id?: any;
    /** 项目列表 */
    project_list?: any;
    // 文件
    file?: any;
    // 是否已发送
    is_send: boolean;

    // 
    appropriation_info?: any;
    ids?: any;
    sp_msg?: any;
    now_donate_ids?: any;

    // 申请步骤
    apply_step?: any;

    // 当前页数
    current: number;
    // 一页展示多少条数据
    pagesize: number;
    // 总数
    total?: number;
    // 拨款弹窗
    modal_visible?: boolean;
    // 选择的数组
    selected_ids: string[];
    // 选择的金额
    selected_money: number;
    // 捐款列表
    donate_list?: any;
    // 搜索关键词
    intention?: string;
    // 拨款的ids
    donate_ids?: any;
}

/**
 * 组件：个人募捐申请页面
 * 个人募捐申请页面
 */
export class RecipientApply extends ReactView<RecipientApplyViewControl, RecipientApplyState> {
    constructor(props: any) {
        super(props);
        this.state = {
            step: -2,
            status: '',
            disabled: false,
            request_url: '',
            apply_info: [],
            society_info: [],
            template_id: '',
            template_list: [],
            project_list: [],
            file: [],
            is_send: false,
            appropriation_info: [],
            ids: [],
            now_donate_ids: [],
            apply_step: [],
            sp_msg: '',

            current: 1,
            pagesize: 50,
            total: 0,
            modal_visible: false,
            selected_ids: [],
            selected_money: 0,
            donate_list: [],
            intention: '',
            donate_ids: [],
        };
    }
    componentWillMount() {
        let request_url = this.props.request_url;
        this.setState({
            request_url
        });
        console.log(this.props);
    }
    componentDidMount() {
        let param = (this.props.match!.params.code && this.props.match!.params.code === 'view') ? { all: true, id: this.props.match!.params.key } : { id: this.props.match!.params.key };

        if (this.props.match!.params.key) {
            request(this, AppServiceUtility.charitable_service.get_charitable_recipient_apply_list_all!(param, 1, 1))
                .then((datas: any) => {
                    let step_no = (datas.result && datas.result[0] && datas.result[0]['new_field'] && datas.result[0]['new_field'][0] && datas.result[0]['new_field'][0]['step_no']) ? datas.result[0]['new_field'][0]['step_no'] : ((datas.result && datas.result[0] && datas.result[0]['step_no']) ? datas.result[0]['step_no'] : -1);
                    let status = (datas.result && datas.result[0] && datas.result[0]['new_field'] && datas.result[0]['new_field'][0] && datas.result[0]['new_field'][0]['status']) ? datas.result[0]['new_field'][0]['status'] : ((datas.result && datas.result[0] && datas.result[0]['status']) ? datas.result[0]['status'] : '未知');
                    let donate_ids = (datas.result && datas.result[0] && datas.result[0]['donate_ids'] && datas.result[0]['donate_ids'][0]) ? datas.result[0]['donate_ids'][0] : [];
                    let now_donate_ids: any = [];
                    donate_ids.map((item: any, index: number) => {
                        now_donate_ids.push(item.id);
                    });
                    let apply_info = (datas.result && datas.result[0]) ? datas.result[0] : [];
                    this.setState({
                        step: step_no,
                        status,
                        now_donate_ids,
                        apply_info,
                    });
                    this.getRecipientStep(apply_info.apply_type);
                    if (donate_ids.length > 0) {
                        this.getDonateList(now_donate_ids);
                    }
                });
        } else {
            // 啥都没有，默认个人申请
            this.setState({
                step: 0,
                status: '待审批',
            });
            this.getRecipientStep('个人');
        }

        // 获取慈善会信息
        request(this, AppServiceUtility.charitable_service.get_charitable_society_list!({}, 1, 1))
            .then((data: any) => {
                if (data.result && data.result[0]) {
                    this.setState({
                        society_info: data.result[0] || [],
                    });
                }
            })
            .catch(error => {
                message.error(error.message);
            });
    }
    getRecipientStep(apply_type: string) {
        // 默认
        apply_type = apply_type || '个人';
        // 获取募捐步骤
        request(this, AppServiceUtility.charitable_service.get_recipient_step!({ 'step_type': apply_type }, 1, 1))
            .then((data: any) => {
                if (data) {
                    this.setState({
                        apply_step: data,
                    });
                } else {
                    message.error(`错误信息：${data}`);
                }
            })
            .catch(error => {
                message.error(error.message);
            });
    }
    getDonateList(value: any) {
        request(this, AppServiceUtility.charitable_service.get_charitable_donate_list_all!({ ids: value, donate_type: '', recipient_id: this.props.match!.params.key }, 1, 99))
            .then((datas: any) => {
                this.setState(
                    {
                        appropriation_info: datas.result || [],
                    },
                );
            });
    }
    handleSubmit(err: any, values: any, child: any) {
        // 个人申请标识
        values['apply_type'] = '个人';
        // 保存
        request(this, AppServiceUtility.charitable_service.update_charitable_recipient_apply!(values))
            .then((data: any) => {
                if (data === 'Success') {
                    message.success(`提交成功！`, 3, () => {
                        child.props.pprops.history.push(ROUTE_PATH.recipientApplyList);
                    });
                } else {
                    message.error(`错误信息：${data}`);
                }
            })
            .catch(error => {
                message.error(error.message);
            });
    }
    // 返回审核列表
    returnList() {
        this.props.history!.push(ROUTE_PATH.recipientApplyList);
    }
    // 拨款
    giveMoney() {
        this.setState({
            modal_visible: true,
        });
    }
    toCharitableAppropriation(id: string) {
        this.props.history!.push(ROUTE_PATH.changeCharitableAppropriation + '/' + id);
    }
    changeStatus(value: any, notice: string) {
        const is_send = this.state.is_send;
        const that = this;
        notice = notice || '操作成功！';
        // 正在发送请求
        if (is_send === true) {
            message.error('请勿操作过快！');
            return;
        }
        this.setState(
            {
                is_send: true,
            },
            () => {
                request(that, AppServiceUtility.charitable_service.update_charitable_recipient_apply!(value))
                    .then((data: any) => {
                        if (data === 'Success') {
                            that.setState({
                                is_send: false,
                            });
                            message.success(notice, 3, () => this.returnList());
                        } else {
                            message.error(data);
                        }
                    }).catch((error: Error) => {
                        message.error(error.message);
                    });
            }
        );

        return;
    }
    setParam(step_no: number, status: string, sp_status: string, notcie: string) {
        let { sp_msg, apply_info } = this.state;
        if (sp_status === '不通过' && sp_msg === '') {
            message.error('不通过请填写原因');
            return;
        }
        let param: any = {
            // 审批标识
            'is_sp': 1,
            // 审批状态
            'sp_status': sp_status,
            // 主数据状态
            'status': status,
            // 申请类型
            'apply_type': apply_info['apply_type'],
            // 审批信息
            'sp_msg': sp_msg,
            // 步骤
            'step_no': step_no,
            // 主键ID
            'id': apply_info['id'],
        };
        // 第三步要提交拨款，要带上选择的捐款id
        if (step_no === 3) {
            param['donate_ids'] = this.state.donate_ids;
        }
        this.changeStatus(param, notcie);
    }
    setRejectReason(e: any) {
        this.setState({
            sp_msg: e.target.value,
        });
    }
    // 返回申请填写表
    returnApplyForm(apply_type: string) {
        const { society_info } = this.state;
        return (
            <Card>
                <ApplyTemplateForm formSubmit={this.handleSubmit} pprops={this.props} apply_type={apply_type} />
                <br />
                <br />
                <SocietyInfo data_info={society_info} />
            </Card>
        );
    }
    // 返回资料审批
    returnInfoSH(apply_type: string) {
        const apply_info = this.state.apply_info;
        let isView = this.props.match!.params.code;
        return (
            <Card>
                <ApplyInfo apply_info={apply_info} />
                {isView ? null : <Row>
                    <br />
                    <Row>不通过请填写原因</Row>
                    <br />
                    <TextArea rows={4} onChange={(e) => { this.setRejectReason(e); }} />
                    <Row type="flex" justify="center" className="ctrl-btns">
                        <Button onClick={() => this.setParam(1, '不通过', '不通过', '')}>不通过</Button>
                        <Button type="primary" onClick={() => this.setParam(1, '待审批', '通过', '')}>审批通过</Button>
                    </Row>
                </Row>}
            </Card>
        );
    }
    // 补全备案号
    returnBeiAnHao() {
        const { apply_info } = this.state;
        let isView = this.props.match!.params.code;
        return (
            <Card>
                <ApplyInfo apply_info={apply_info} />
                {isView ? null : <Row>
                    <br />
                    <Row>补全备案号</Row>
                    <br />
                    <TextArea rows={4} onChange={(e) => { this.setRejectReason(e); }} />
                    <Row type="flex" justify="center" className="ctrl-btns">
                        <Button type="primary" onClick={() => this.setParam(2, '待审批', '通过', '提交备案号成功！')}>提交备案号</Button>
                    </Row>
                </Row>}
            </Card>
        );
    }
    // 选择拨款
    returnGiveMoney() {
        const { apply_info, current, pagesize } = this.state;
        let isView = this.props.match!.params.code;
        return (
            <Card>
                <ApplyInfo apply_info={apply_info} />
                {isView ? null : <Row>
                    <br />
                    <Row type="flex" justify="center" className="ctrl-btns">
                        <Button type="primary" onClick={() => this.selectdata(current, pagesize, apply_info['intention'])}>选择拨款</Button>
                    </Row>
                </Row>}
            </Card >
        );
    }
    // 拨款审批
    giveMoneySH() {
        let columns_data_source = [{
            title: '所用捐款',
            dataIndex: 'donate_name',
            key: 'donate_name',
        }, {
            title: '使用金额',
            dataIndex: 'freeze_money',
            key: 'freeze_money',
        }];
        const { apply_info, appropriation_info } = this.state;
        let isView = this.props.match!.params.code;
        return (
            <Card>
                <ApplyInfo apply_info={apply_info} />
                {isView ? null : <Row>
                    <br />
                    <Row>使用捐款信息</Row>
                    <br />
                    <Table pagination={false} columns={columns_data_source} dataSource={appropriation_info} />
                    <br />
                    <Row>不通过请填写原因</Row>
                    <br />
                    <TextArea rows={4} onChange={(e) => { this.setRejectReason(e); }} />
                    <br />
                    <Row type="flex" justify="center" className="ctrl-btns">
                        <Button onClick={() => this.setParam(4, '不通过', '不通过', '')}>不通过</Button>&nbsp;&nbsp;<Button type="primary" onClick={() => this.setParam(4, '待审批', '通过', '')}>审批通过</Button>
                    </Row>
                </Row>}
            </Card>
        );
    }
    // 拨款确认
    giveMoneyConfirm() {
        const apply_info = this.state.apply_info;
        let isView = this.props.match!.params.code;
        return (
            <Card>
                <Result
                    status="info"
                    title={`请将款项拨款到账户：${apply_info.account_number}`}
                />
                <br />
                {isView ? null : <Row>
                    <Row type="flex" justify="center" className="ctrl-btns">
                        <Button onClick={() => this.setParam(5, '通过', '通过', '操作成功，审批已完成！')}>确认已拨款</Button>
                    </Row>
                </Row>}
            </Card>
        );
    }
    onTableChange = (page: number, pagesize: number) => {
        let apply_info = this.state.apply_info;
        this.selectdata(page, pagesize, apply_info['intention']);
    }
    onTableShowSizeChange = (current: number, pagesize: number) => {
        let apply_info = this.state.apply_info;
        this.selectdata(current, pagesize, apply_info['intention']);
    }
    // 搜索操作封装
    selectdata = (current: number, pagesize: number, intention: string) => {
        current = current || this.state.current;
        pagesize = pagesize || this.state.pagesize;
        intention = intention || this.state.apply_info['intention'];
        let param: any = intention ? { intention: intention } : {};
        param.donate_type = '';
        param.status = '通过';
        param.pay_status = '已付款';
        request(this, AppServiceUtility.charitable_service.get_charitable_donate_list_all!(param, 1, 99))
            .then((datas: any) => {
                this.setState({
                    selected_ids: [],
                    selected_money: 0,
                    donate_list: datas.result,
                    modal_visible: true,
                });
            });
    }
    // 搜索操作
    searchList(value: any) {
        this.setState(
            {
                intention: value,
                selected_ids: [],
                selected_money: 0,
            },
            () => {
                this.selectdata(this.state.current, this.state.pagesize, value);
            }
        );
    }
    // 判断元素是否在数组里，id为判断基准
    inArray(id: string, array: any) {
        for (let i in array) {
            if (array[i]) {
                if (array[i]['id'] === id) {
                    return true;
                }
            }
        }
        return false;
    }
    // 选择和取消选择的操作
    chooseThis(e: any, item: any) {
        let { selected_ids, selected_money, apply_info } = this.state;
        let apply_money = apply_info['apply_money'];
        if (this.inArray(item.id, selected_ids)) {
            // 已选择，是取消操作
            let new_ids: string[] = [];
            let new_money: number = 0;
            for (let i in selected_ids) {
                if (selected_ids[i]) {
                    if (selected_ids[i]['id'] !== item.id) {
                        // 重新赋值操作
                        let result = this.pipeiCore(new_money, selected_ids[i], apply_money);
                        new_ids.push(result['item']);
                        new_money = result['selected_money'];
                    }
                }
            }
            selected_ids = new_ids;
            selected_money = new_money;
        } else {
            // 新选择的

            // 判断是否选择足够了
            if (selected_money > apply_money) {
                // 不可能选择超过的
                message.error('数据出错，请刷新重试！');
                return;
            } else if (selected_money === apply_money) {
                message.info('已超出所需金额！');
                return;
            }

            let result = this.pipeiCore(selected_money, item, apply_money);
            selected_ids.push(result['item']);
            selected_money = result['selected_money'];
        }
        this.setState({
            selected_ids,
            selected_money,
        });
    }
    // 匹配的核心操作
    pipeiCore(selected_money: any, item: any, apply_money: any) {
        if (selected_money + item.surplus_money <= apply_money) {
            // 这是已经占用的金额，做个标识
            item['occupy_money'] = item.surplus_money;
            // 如果已选的+剩余的小于等于所需，直接push
            selected_money += item.surplus_money;
        } else {
            // 这是已经占用的金额，做个标识
            item['occupy_money'] = apply_money - selected_money;
            // 所选的加上新选的超过了，也是直接push，但是金额直接等于所需金额
            selected_money = apply_money;
        }
        return {
            item,
            selected_money,
        };
    }
    // 提交审核并跳转到审核列表
    submit() {
        let { selected_ids, selected_money, apply_info } = this.state;
        if (selected_ids.length < 1) {
            message.error('请选择捐款！');
            return;
        }
        if (selected_money < apply_info['apply_money']) {
            message.error('所选捐款金额不足！');
            return;
        }
        let donate_ids: any = [];
        selected_ids.map((item: any, index) => {
            if (item.occupy_money > 0) {
                donate_ids.push({
                    id: item.id,
                    occupy_money: item.occupy_money,
                });
            }
        });

        if (donate_ids.length < 1) {
            message.error('数据出错，请刷新重试！');
            return;
        }

        this.setState(
            {
                donate_ids,
            },
            () => {
                this.setParam(3, '待审批', '通过', '提交拨款成功！');
            }
        );
    }
    // 显示模态框
    showModal() {
        this.setState({
            modal_visible: true,
        });
    }
    // 隐藏模态框
    hideModal() {
        this.setState({
            modal_visible: false,
        });
    }
    render() {
        let { step, status, apply_info, apply_step, selected_ids, total, pagesize, selected_money, donate_list } = this.state;
        let stepStatus: any = {};
        if (status === '不通过') {
            stepStatus.status = 'error';
        }
        // 申请类型
        const apply_type = apply_info && apply_info['apply_type'] ? apply_info['apply_type'] : '个人';
        console.log('111', apply_type, step, status);
        // step为-1代表完成了，取数组长度
        step = step === -1 ? apply_step.length - 1 : step;
        return (
            <MainContent>
                <Modal
                    className="charitable-appropriation-modal"
                    width={1400}
                    visible={this.state.modal_visible}
                    okText="OK"
                    cancelText="返回"
                    onOk={() => this.hideModal()}
                    onCancel={() => this.hideModal()}
                    okButtonProps={{ className: 'okBtn' }}
                >
                    <Row className="charitable-appropriation-list">
                        <Row type="flex" justify="space-between" align="middle">
                            <Col span={32}>
                                <Search
                                    defaultValue={apply_info['description'] || ''}
                                    placeholder="请输入捐款意向/金额"
                                    enterButton="一键匹配"
                                    size="large"
                                    onSearch={(value) => this.searchList(value)}
                                />
                            </Col>
                            <Col>
                                &nbsp;&nbsp;&nbsp;&nbsp;募捐人：{apply_info['apply_name'] || ''}&nbsp;&nbsp;&nbsp;&nbsp;申请金额：{apply_info['apply_money'] || 0}&nbsp;&nbsp;&nbsp;&nbsp;已选择：￥{selected_money}
                            </Col>
                        </Row>
                        <br />
                        <Row gutter={16} className="list-content">
                            {(() => {
                                if (donate_list.length > 0) {
                                    return donate_list!.map((item: any, index: number) => {
                                        let cls = this.inArray(item.id, selected_ids) === true ? 'project-section selected' : 'project-section';
                                        return (
                                            <Col key={index} className="projectlist">
                                                <Row className={cls} onClick={(e) => { this.chooseThis(e, item); }}>
                                                    <Row className="detail">
                                                        <Row>
                                                            捐款名义：{item.donate_name || ''}
                                                        </Row>
                                                        <Row className="price">
                                                            捐款金额：￥<strong>{item.donate_money || 0}</strong>
                                                        </Row>
                                                        <Row className="price">
                                                            已使用金额：￥<strong>{item.payed_money || 0}</strong>
                                                        </Row>
                                                        <Row className="price">
                                                            冻结金额：￥<strong>{item.freeze_money || 0}</strong>
                                                        </Row>
                                                        <Row className="price">
                                                            剩余金额：￥<strong>{item.surplus_money || 0}</strong>
                                                        </Row>
                                                        <Row className="intention">
                                                            捐款意向：{item.donate_intention || '暂无'}
                                                        </Row>
                                                    </Row>
                                                </Row>
                                            </Col>
                                        );
                                    });
                                } else {
                                    return <Row className="empty-data">
                                        <Row type="flex" justify="center">暂无数据</Row>
                                    </Row>;
                                }
                            })()}
                        </Row>
                        {(() => {
                            if (selected_ids.length > 0) {
                                return (
                                    <Row type="flex" justify="center" className="submit-row">
                                        <Button onClick={() => this.submit()}>提交审核</Button>
                                    </Row>
                                );
                            }
                            return null;
                        })()}
                        <Pagination
                            showSizeChanger={true}
                            onChange={this.onTableChange}
                            onShowSizeChange={this.onTableShowSizeChange}
                            total={total}
                            pageSize={pagesize}
                        />
                    </Row>
                </Modal>
                <Steps current={step} {...stepStatus} style={{ background: "white", padding: "25px" }}>
                    {apply_step.map((item: any, index: number) => {
                        return (
                            <Step key={index} title={item.step_name} />
                        );
                    })}
                </Steps>
                {(() => {
                    if (status === '不通过') {
                        return (
                            <Card>
                                <Result
                                    status="error"
                                    title="审批不通过"
                                    subTitle={'不通过原因：' + (apply_info['sp_msg'] || '暂无')}
                                />
                            </Card>
                        );
                    } else if (status === '通过') {
                        return (
                            <Card>
                                <Result
                                    status="success"
                                    title="完成"
                                    subTitle={`已拨款到申请账户：${apply_info.account_number}`}
                                />
                            </Card>
                        );
                    } else {
                        if (step === 0) {
                            // 申请表
                            return this.returnApplyForm(apply_type);
                        } else if (step === 1) {
                            // 资料审批
                            return this.returnInfoSH(apply_type);
                        } else if (step === 2) {
                            // 补全备案号
                            return this.returnBeiAnHao();
                        } else if (step === 3) {
                            // 前往拨款
                            return this.returnGiveMoney();
                        } else if (step === 4) {
                            // 拨款审批
                            return this.giveMoneySH();
                        } else if (step === 5) {
                            // 拨款确认
                            return this.giveMoneyConfirm();
                        }
                    }
                    return null;
                })()}
            </MainContent>
        );
    }
}

/**
 * 控件：个人募捐申请页面
 * 个人募捐申请页面
 */
@addon('RecipientApply', '个人募捐申请页面', '个人募捐申请页面')
@reactControl(RecipientApply, true)
export class RecipientApplyViewControl extends ReactViewControl {
    /** 视图权限 */
    public permission?: Permission;
    /** 请求接口名 */
    public request_url?: string;
    /** 获取权限接口类 */
    public permission_class?: any;
    /** 获取权限接口方法名 */
    public get_permission_name?: string;
    /** 查询权限 */
    public select_permission?: string;
    /** 编辑权限 */
    public edit_permission?: string;
    /** 删除权限 */
    public delete_permission?: string;
    /** 新增权限 */
    public add_permission?: string;
}